package cn.rwklyd.BookKeeping.handler;
import cn.rwklyd.BookKeeping.exception.CustomerAuthenticationException;
import cn.rwklyd.BookKeeping.pojo.Result;
import com.alibaba.fastjson2.JSON;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;
import cn.rwklyd.BookKeeping.constant.MessageConstant;

/**
 * 表单登录失败处理器(前后端分离不使用)
 */
@Slf4j
@Component
public class LoginFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        // 设置客户端响应编码格式
        response.setContentType("application/json;charset=utf-8");
        // 获取输出流
        ServletOutputStream outputStream = response.getOutputStream();
        String message = null;
        int code = 601;
        // 判断异常类型
        if (exception instanceof AccountExpiredException) {
            message = "账号过期";
        } else if (exception instanceof BadCredentialsException) {
            if (exception.getCause() instanceof UsernameNotFoundException) {
                message = "用户不存在";
            } else {
                message = "密码错误";
            }
        } else if (exception instanceof CredentialsExpiredException) {
            message = "密码过期";
        } else if (exception instanceof DisabledException) {
            message = "账号被禁用";
        } else if (exception instanceof LockedException) {
            message = "账号被锁定";
        } else if (exception instanceof InternalAuthenticationServiceException) {
            message = "用户不存在";
        } else if (exception instanceof CustomerAuthenticationException) {
            message = exception.getMessage();
            log.info(exception.getMessage());
            
            // 如果是令牌失效的情况，则返回600（访问令牌过期）
            if(exception.getMessage().equals(MessageConstant.REFRESH_TOKEN_EXPIRED) ||
                    exception.getMessage().equals(MessageConstant.USER_NOT_LOGIN) ||
                    exception.getMessage().equals(MessageConstant.TOKEN_INVALID)
            ){
                code = 600;
            } else {
                code = 601;  // 其他错误
            }
        } else {
            message = "登录失败";
        }

        // 将错误信息转换成JSON格式返回给客户端
        String result = JSON.toJSONString(Result.error(code, message));
        outputStream.write(result.getBytes("UTF-8"));
        outputStream.flush();
        outputStream.close();
    }

}
